var express = require('express');
var router = express.Router();
let md5 = require('md5');
let config = require('../config/config');
let {User, Session, getModelByName, isPhoneAndEMailRepeat} = require('../database/sequelize');
let {isEmail, isPhone} = require('../utils/utils');
let {successResult, paramsError, failError} = require('../base/result');

router.get('\/*\/list', async function (req, res, next) {

  let page = req.body.page;
  let order = req.body.order;
  let sortBy = req.body.sortBy;
  let limit = req.body.limit;

  let tableName = req.path.split("/")[1];


  //过滤
  if (!page || page < 1 || isNaN(page)) {
    page = 1
  }

  if (order !== 'desc' && order !== 'asc') {
    order = 'desc';
  }

  if (sortBy) {
    sortBy = "id"
  }

  if (!limit || limit < 1 || isNaN(limit)) {
    limit = 10;
  }
  let data = [];

  if (!getModelByName(tableName)) {
    next();
  }

  await getModelByName(tableName).findAll({offset: (page - 1) * limit, limit: limit})
    .then(user => {
      for (let item of user) {
        data.push(item.dataValues);
      }
    });


  if (data) {
    res.send(successResult(data));
  } else {
    res.send(failError());
  }

});

router.get('\/*\/detail', async function (req, res, next) {

  let id = req.body.id;
  let tableName = req.path.split("/")[1];
  //过滤
  if (!id || isNaN(id)) {
    res.send(paramsError());
    return
  }

  if (!getModelByName(tableName)) {
    next();
  }

  let data = [];

  data = await getModelByName(tableName).findById(id);


  if (data) {
    res.send(successResult(data));
  } else {
    res.send(failError());
  }


});


router.post('\/*\/delete', async function (req, res, next) {

  let id = req.body.id;

  let tableName = req.path.split("/")[1];

  //过滤
  if (!id || isNaN(id)) {
    res.send(paramsError());
    return
  }

  if (!getModelByName(tableName)) {
    next();
  }

  let data = {};

  data = await getModelByName(tableName).destroy({
    where: {id: id}
  })

  if (data) {
    res.send(successResult(data));
  } else {
    res.send(failError());
  }

});

router.post('\/*\/add', async function (req, res, next) {

  let params = req.body;

  delete params.uid;

  let tableName = req.path.split("/")[1];

  //过滤
  if (!id || isNaN(id)) {
    res.send(paramsError());
    return
  }

  //过滤
  if (tableName === "user") {
    if (!isPhone(params.phone) || !isEmail(params.email)) {
      res.send(failError());
      return
    }
    params.password = md5(config.salt + params.password);

    let isRepeat = await isPhoneAndEMailRepeat(params.phone, params.email);

    if (isRepeat) {
      res.send({"success": false, errCode: -1, "msg": "账号或者邮箱重复"});
      return
    }
  }

  let data = null;

  try {
    data = await getModelByName(tableName).create({
      id: null,
      ...params,
      updated_at: new Date().getTime() / 1000,
      created_at: new Date().getTime() / 1000
    })
  } catch (e) {
    console.log(e);
  }


  if (data) {
    res.send(successResult(data));
  } else {
    res.send(failError());
  }

});

router.post('\/*\/update', async function (req, res, next) {

  let id = req.body.id;

  let params = req.body;

  delete params.uid;
  delete params.id;

  let tableName = req.path.split("/")[1];

  //过滤
  if (!id || isNaN(id)) {
    res.send(paramsError());
    return
  }

  //过滤
  if (tableName === "user") {
    if (!isPhone(params.phone) || !isEmail(params.email)) {
      res.send(failError());
      return
    }
    params.password = md5(config.salt + params.password);

    let isRepeat = await isPhoneAndEMailRepeat(params.phone, params.email);

    if (isRepeat) {
      res.send({"success": false, errCode: -1, "msg": "账号或者邮箱重复"});
      return
    }
  }

  let data = null;

  try {
    data = await getModelByName(tableName).update({
      ...params,
      updated_at: new Date().getTime() / 1000
    }, {
      where: {id: id}
    })
  } catch (e) {
    console.log(e);
  }


  if (data) {
    res.send(successResult(data));
  } else {
    res.send(failError());
  }

});


module.exports = router;
